﻿using UnityEngine;
using System.Collections.Generic;
using System.Text;

namespace GameBasic.BehaviorTree
{
    public class BhvNode
    {
        // Data
        public Bhv.Type type;
        public string name;
        public Object obj;

        public List<BhvNode> children = new List<BhvNode>();

        // Runtime
        public string[] funcArgs;

        public int ChildCount => children?.Count ?? 0;

        public bool HasChild()
        {
            return ChildCount > 0;
        }

        public void SetData(BhvData data)
        {
            type = data.type;
            name = data.name;
            obj = data.obj;
        }

        public BhvData GetData()
        {
            BhvData data = new BhvData();
            data.type = type;
            data.name = name;
            data.obj = obj;
            return data;
        }

        #region Text
        public override string ToString()
        {
            string result = null;

            bool hasName = !string.IsNullOrEmpty(name);


            if (type == Bhv.Type.None)
            {
                if (hasName)
                    result = name;
                else
                    result = type.ToString();
            }
            else if (type == Bhv.Type.Action)
            {
                if (hasName)
                    result = name;
                else if (obj != null)
                    result = obj.name;
            }
            else
            {
                result = type.ToString();
                if (hasName)
                    result += "(" + name + ")";
            }

            return result;
        }

        public string GetHierarchyText(StringBuilder sb = null)
        {
            if(sb == null)
                sb = new StringBuilder();
            GetHierarchyText(this, sb);
            return sb.ToString();
        }

        public static void GetHierarchyText(BhvNode node, StringBuilder sb)
        {
            Bhv.Type type = node.type;

            string text = node.ToString();

            if (type == Bhv.Type.None)
            {
                sb.Append(text);
            }
            else if (type == Bhv.Type.Action)
            {
                sb.Append(text);
            }
            else
            {
                sb.Append(text).Append("{\n");

                var children = node.children;
                for (int i = 0, length = node.ChildCount; i < length; i++)
                {
                    if (i > 0)
                        sb.Append(", ");

                    var b = children[i];
                    GetHierarchyText(b, sb);
                }

                sb.Append("}\n");
            }
        }
        #endregion
    }
}